--
-- Author: mengjie
-- Date: 2016-04-13 13:00:21
--
local LineBlock = import("..view.LineBlock")
local BaseScene = class("BaseScene", function()
    return display.newScene("BaseScene")
end)
function BaseScene:ctor()
	self.lines={}
	self.index=2
	self.headIndex = 1
	self.moveSpeed = 0.1
	local line
	local lineType = BaseBlockTYPE.NORMAL
	for i=1,CELL_WIDTH_COUNT+2 do
		if i ==1 then
			lineType=BaseBlockTYPE.STARTING
		elseif i ==2 then
			lineType=BaseBlockTYPE.FIRST
		else
			lineType=BaseBlockTYPE.NORMAL
		end
		line=LineBlock.new(lineType)
		line:setPosition(0, (i-1)*CELL_HEIGHT+i)
		self:addChild(line)
		self.lines[i]=line
	end
	self:setNodeEventEnabled(true)
	l_soundMananegr.reset()
end
function BaseScene:onClick()
	l_soundMananegr.playClick()
end
function BaseScene:onErrorClick()
	l_soundMananegr.playError()
end
function BaseScene:getNewLine(line)
	line:changeType(BaseBlockTYPE.NORMAL)
end
function BaseScene:moveNext()
	-- print("moveNext")
	for i,v in ipairs(self.lines) do
		transition.stopTarget(v)
		if i==1 then
			local sequence = transition.sequence({
			    cc.MoveTo:create(self.moveSpeed, cc.p(0, (i-2)*CELL_HEIGHT+i-2)),
			    cc.DelayTime:create(1/60),
			    cc.CallFunc:create(function ( ... )
			    	 self.index=self.index-1
			        local len = #self.lines
			        local line = table.remove(self.lines,1)
			        self.lines[len]=line
			        line:setPositionY((len-2)*CELL_HEIGHT+len)
			        self:getNewLine(line)
			    end),
			})
			v:runAction(sequence)
			
		else
	    	transition.moveTo(v,{time=self.moveSpeed,y=(i-2)*CELL_HEIGHT+i-2,x=0})
	    end
	end
end
function BaseScene:onEnter()
	self:setEventListener()
end
function BaseScene:setEventListener()
   
    local listener = cc.EventListenerTouchAllAtOnce:create()
    listener:registerScriptHandler(function(touchs, event) 
      
    end, cc.Handler.EVENT_TOUCHES_BEGAN  )

    listener:registerScriptHandler(function(touchs, event)
        
    end, cc.Handler.EVENT_TOUCHES_MOVED)

    listener:registerScriptHandler(function(touchs, event) 
         if #touchs ~= 0 then
			local touch = touchs[1]
			if touch then
				local celX,celY=self:getClickCell(touch)
				if self.index>=celY then
					if self.index == celY and self.lines[celY]:clickCell(celX) then
						self:onClick()
						self.index=self.index+1
					else
						self:onErrorClick()
					end
				end
			end
        end
    end, cc.Handler.EVENT_TOUCHES_ENDED)

    local eventDispatcher = self:getEventDispatcher()
    eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
end
function BaseScene:getClickCell(touch)
	local line = self.lines[self.headIndex]
	local _y = line:getPositionY()
	local clickPoint = touch:getLocation()
	clickPoint.y = clickPoint.y -_y
	return math.ceil(clickPoint.x/CELL_WIDTH),math.ceil(clickPoint.y/CELL_HEIGHT)
end
return BaseScene